package utils

import (
	"math/rand"
	"time"
)

type WeightMap[K comparable] map[K]int32

func NewWeightMap[K comparable](m ...map[K]int32) WeightMap[K] {
	n := make(map[K]int32)
	for _, s := range m {
		for k, v := range s {
			n[k] = v
		}
	}
	return n
}

func (w WeightMap[K]) Rand() (key K, ok bool) {
	var weightSum, weightNum int32
	for _, v := range w {
		weightSum += v
	}
	if weightSum <= 0 {
		return
	}
	randInt := rand.Int31n(weightSum)
	for k, v := range w {
		weightNum += v
		if randInt < weightNum {
			return k, true
		}
	}
	return
}

func RandInt(start int, end int) int {
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(end-start) + start
}
